package com.example.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.book.common.Constants;
import com.example.book.common.Result;
import com.example.book.entry.User;
import com.example.book.mapper.UserMapper;
import com.example.book.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService{

    @Autowired
    private UserMapper userMapper;

//    注册
    @Override
    public Result userRegister(User user) {
//        检查用户名是否已存在
        String check = userMapper.userCheck(user.getUsername());
        if(check != null){
            return Result.error("300","用户已存在");
        }
        try {
            userMapper.userRegister(user);
//            注册成功时返回id
            Integer id = user.getId();
            return Result.success("注册成功",id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }

    //    登录
    @Override
    public Result login(User user){
        Result userInfo = getUserInfo(user);
        return userInfo;
    }
    private Result getUserInfo(User user){
//        检查用户名和密码是否输入
        if(user.getUsername().isEmpty() || user.getPassword().isEmpty()){
            return Result.error(Constants.CODE_500,"请输入用户名和密码");
        }
        String username = user.getUsername();
        String password = user.getPassword();
//        获取数据库的用户名和密码
        User selectUser = userMapper.selectUser(username, password);
//        当数据查询不到数据时，返回提示错误
        if(selectUser == null){
            return Result.error(Constants.CODE_500,"用户名或密码错误，请重试");
        }
//        判断用户账号是否禁用 contains():检查一个字符串中是否包含指定的字符串
        if (selectUser.getStatus().contains("1")){
            return Result.error(Constants.CODE_400,"您的账号已禁用");
        }
        return Result.success("success",selectUser);
    }
}
